package vip.wangwenhao.gateway.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
import vip.wangwenhao.common.util.BeanUtils;
import vip.wangwenhao.common.enums.ResultCode;
import vip.wangwenhao.common.exception.LimitException;
import vip.wangwenhao.common.result.Result;

import java.util.Map;

/**
 * @author wangwenhao
 */

@Slf4j
@Component
public class HystrixFallbackHandler implements HandlerFunction<ServerResponse> {


    @Override
    public Mono<ServerResponse> handle(ServerRequest serverRequest) {
        Map<String, Object> attributes = serverRequest.attributes();
        Object obj = attributes.get(ServerWebExchangeUtils.HYSTRIX_EXECUTION_EXCEPTION_ATTR);
        Result result;
        if (null != obj) {
            Map<String, Object> map = BeanUtils.beanToMap(obj);
            String exceptionType = (String) map.get("@type");
            if (LimitException.class.getName().equals(exceptionType)) {
                result = Result.fail(ResultCode.TOO_MANY_REQUESTS);
            } else {
                result = Result.fail(ResultCode.ERROR_SERVER_FAILED);
            }
        } else {
            result = Result.fail(ResultCode.ERROR_SERVER_FAILED);
        }
        return ServerResponse
                .status(HttpStatus.OK)
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .body(BodyInserters.fromObject(result));
    }
}